using B.S.XZYData.Api.Wrter.Application.Command.WorkOrder;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;

namespace B.S.XZYData.Api.Wrter.Application.Handler.WorkOrder
{
    /// <summary>
    /// 删除工单处理器
    /// </summary>
    public class DeleteWorkOrderHandler : IRequestHandler<DeleteWorkOrderCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<WorkOrderModel> _workOrderRepo;
        private readonly IBaseRepository<WorkOrderProcessModel> _workOrderProcessRepo;
        private readonly IBaseRepository<WorkOrderAssignModel> _workOrderAssignRepo;
        private readonly ILogger<DeleteWorkOrderHandler> _logger;

        public DeleteWorkOrderHandler(
            IBaseRepository<WorkOrderModel> workOrderRepo,
            IBaseRepository<WorkOrderProcessModel> workOrderProcessRepo,
            IBaseRepository<WorkOrderAssignModel> workOrderAssignRepo,
            ILogger<DeleteWorkOrderHandler> logger)
        {
            _workOrderRepo = workOrderRepo;
            _workOrderProcessRepo = workOrderProcessRepo;
            _workOrderAssignRepo = workOrderAssignRepo;
            _logger = logger;
        }

        public async Task<ApiResult<bool>> Handle(DeleteWorkOrderCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<bool>();

            try
            {
                // 设置默认操作人
                if (string.IsNullOrWhiteSpace(request.OperateBy))
                {
                    request.OperateBy = "System";
                }

                // 检查工单是否存在
                var workOrder = await _workOrderRepo.GetValue(request.Id);
                if (workOrder == null)
                {
                    res.Code = ApiEnum.Error;
                    res.Msg = "工单不存在";
                    return res;
                }

                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    // 获取该工单的所有工序
                    var processes = _workOrderProcessRepo.GetAll()
                        .Where(x => x.WorkOrderId == request.Id)
                        .ToList();

                    // 删除所有相关的分派记录
                    foreach (var process in processes)
                    {
                        var assigns = _workOrderAssignRepo.GetAll()
                            .Where(x => x.WorkOrderProcessId == process.Id)
                            .ToList();

                        foreach (var assign in assigns)
                        {
                            await _workOrderAssignRepo.DeleteAsync(assign.Id);
                        }
                    }

                    // 删除所有工序记录
                    foreach (var process in processes)
                    {
                        await _workOrderProcessRepo.DeleteAsync(process.Id);
                    }

                    // 删除工单主记录
                    await _workOrderRepo.DeleteAsync(workOrder.Id);

                    scope.Complete();

                    _logger.LogInformation($"删除工单成功：{workOrder.Code}，操作人：{request.OperateBy}");

                    res.Data = true;
                    res.Code = ApiEnum.Success;
                    res.Msg = "删除工单成功";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除工单失败，工单ID：{request.Id}，操作人：{request.OperateBy}");
                res.Code = ApiEnum.Error;
                res.Msg = $"删除工单失败：{ex.Message}";
            }

            return res;
        }
    }
}
